package com.ccteam.fluidmusic.ui.setting

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import cn.hutool.core.lang.Validator
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentEditNewPhoneBinding
import com.ccteam.fluidmusic.utils.EventObserver
import com.ccteam.fluidmusic.utils.VerifyCodeCountDownTimer
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.widget.SNACKBAR_BOTTOM
import com.ccteam.fluidmusic.widget.snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/4/16
 *
 * 修改新手机号 Fragment
 */
@AndroidEntryPoint
class EditNewPhoneFragment: Fragment() {

    private var _binding: FragmentEditNewPhoneBinding? = null
    private val binding get() = _binding!!

    private val editNewPhoneViewModel by viewModels<EditNewPhoneViewModel>()

    private val verifyCodeCountDownTimer = VerifyCodeCountDownTimer()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentEditNewPhoneBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        viewLifecycleOwner.lifecycleScope.launch {
            verifyCodeCountDownTimer.countDown.collectLatest {
                if(it is VerifyCodeCountDownTimer.Status.Timing){
                    updateTiming(it.currentCountDownNum)
                } else {
                    updateNotTiming()
                }
            }
        }

        editNewPhoneViewModel.enableCountDown.observe(viewLifecycleOwner,EventObserver{
            if(it){
                verifyCodeCountDownTimer.start()
            }
        })

        editNewPhoneViewModel.enableEditNewPhoneButton.observe(viewLifecycleOwner, {
            binding.btnEditNewPhone.isEnabled = it
        })

        editNewPhoneViewModel.enableVerifyCodeButton.observe(viewLifecycleOwner, {
            binding.btnVerifyNewPhone.isEnabled = it && verifyCodeCountDownTimer.countDown.value !is VerifyCodeCountDownTimer.Status.Timing
        })

        editNewPhoneViewModel.snackLoadMessage.observe(viewLifecycleOwner, EventObserver{
            binding.btnEditNewPhone.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Success){
                Toast.makeText(requireContext().applicationContext,
                    getString(R.string.description_success_edit_logout), Toast.LENGTH_SHORT).show()
                requireActivity().finish()
            } else if(it is LoadMessage.Error){
                view.snackbar(it.errorMessage.description.toString(), SNACKBAR_BOTTOM).show()
            }
        })

        /**
         * 观察电话号码输入框，实时检测电话号码合法性
         */
        binding.editNewPhone.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.addTextChangedListener {
                val isMobile = Validator.isMobile(it.toString())
                editNewPhoneViewModel.setPhoneSuccess(isMobile)
            }
        }

        binding.editNewPhoneVerify.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.addTextChangedListener {
                editNewPhoneViewModel.setVerifyCodeSuccess(it.toString().isNotEmpty())
            }
        }

        binding.btnVerifyNewPhone.setProgressButtonOnClickListener{
            editNewPhoneViewModel.getVerification(
                binding.editNewPhone.editText?.text.toString()
            )
        }

        binding.btnEditNewPhone.setProgressButtonOnClickListener{
            editNewPhoneViewModel.editNewPhone(
                binding.editNewPhone.editText?.text.toString(),
                binding.editNewPhoneVerify.editText?.text.toString()
            )
        }
    }

    private fun updateTiming(countDownNum: Int){
        binding.btnVerifyNewPhone.isEnabled = false
        binding.btnVerifyNewPhone.text = countDownNum.toString()
    }

    private fun updateNotTiming(){
        binding.btnVerifyNewPhone.isEnabled = true && editNewPhoneViewModel.enableVerifyCodeButton.value == true
        binding.btnVerifyNewPhone.text = getString(R.string.description_get_verification)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        verifyCodeCountDownTimer.cancel()

        _binding = null
    }
}